package com.gopay.scheduler.job;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.gopay.common.Result;
import com.gopay.common.domain.bank.wechat.scan.cmbc.MerchantQuery;
import com.gopay.common.domain.cust.CustSettledInfo;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.bank.ScanPayMerchantService;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.common.BizMerchantSettledConstants;
import com.gopay.scheduler.dao.MerchantSettledInfoDAO;

/**
 * Created by liyang on 2017/4/11.
 */
public class MerSettleStateQueryJob extends GopayBaseJob {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource(name = "scanPayMerchantServiceClient")
	private ScanPayMerchantService scanPayMerchantService;

	@Autowired
	private MerchantSettledInfoDAO merchantSettledInfoDAO;

	@Override
	protected void doJobInternal() {

		logger.info("商户入驻状态查询job开始*****************");
		
		List<CustSettledInfo> list = merchantSettledInfoDAO
				.getCustSettledInfoByState(BizMerchantSettledConstants.SETTLED_AUDIT);
		
		if (null != list && list.size() > 0) {
			
			for (CustSettledInfo custSettledInfo : list) {
				MerchantQuery req = new MerchantQuery();
				req.setMerchantId(custSettledInfo.getMerchantCode());
				if(BizMerchantSettledConstants.ZFBZF.equals(custSettledInfo.getType())){
					req.setExtend1(BizMerchantSettledConstants.ZFBZF);
				}
				if(BizMerchantSettledConstants.WXZF.equals(custSettledInfo.getType())){
					req.setExtend1(BizMerchantSettledConstants.WXZF);
				}
				try {
					Result res = scanPayMerchantService.merchantQuery(req);
					if (res.isSuccess()) {
						MerchantQuery messageRes=(MerchantQuery)res.getDefaultModel();
						custSettledInfo.setStat(BizMerchantSettledConstants.SETTLED_SUCCESS);
						custSettledInfo.setBankMerchantCode(messageRes.getMerchantCode());
						custSettledInfo.setErrorMsg("入驻成功");
						custSettledInfo.setLastUpdTs(DateUtils.getSystemDate());
						merchantSettledInfoDAO.update(custSettledInfo);
						logger.info("商户:"+custSettledInfo.getCustId()+"入驻"+custSettledInfo.getType()+"成功!");
					} else if (res.getResultCode().equals("200012")) {
						logger.info("商户:"+custSettledInfo.getCustId()+"入驻"+custSettledInfo.getType()+"审核中!");
					} else{
						logger.info("商户:"+custSettledInfo.getCustId()+"入驻"+custSettledInfo.getType()+"失败!失败描述为："+res.getErrorMsg());
					}					
				} catch (GopayException e) {
					e.printStackTrace();
				}
			}
		}
		logger.info("商户入驻状态查询job结束*****************");
	}
}
